package eztools

import (
	"github.com/BurntSushi/toml"
	"github.com/Xuanwo/go-locale"
	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
	"golang.org/x/text/language/display"
)

var (
	i18nBundle    *i18n.Bundle
	i18nLocalizer *i18n.Localizer
)

const i18nFmt = "toml"

// InitLanguages initialize resources for i18n
// 1/4
func InitLanguages() {
	i18nBundle = i18n.NewBundle(language.English)
	i18nBundle.RegisterUnmarshalFunc(i18nFmt, toml.Unmarshal)
}

// AddLanguage add a language resource
// 2*n/4
/* Example: ID = "translated string"
AddLanguage([]byte(`
		StrFlw = "flow"
		StrAll = "select all"
	`), "en"))
*/
func AddLanguage(language, translations string) {
	if i18nBundle == nil {
		return
	}
	i18nBundle.MustParseMessageFileBytes([]byte(translations),
		language+"."+i18nFmt)
}

// LoadLanguage load language of system
// 3/4
func LoadLanguage(lang string) (string, error) {
	if len(lang) < 1 {
		tag, err := locale.Detect()
		if err != nil {
			return "", err
		}
		lang = tag.String()
	}
	i18nLocalizer = i18n.NewLocalizer(i18nBundle, lang)
	return lang, nil
}

// GetLanguageStr returns translated string by ID
// 4*n/4
func GetLanguageStr(id string) (string, error) {
	if i18nLocalizer == nil {
		return "", ErrOutOfBound
	}
	return i18nLocalizer.Localize(&i18n.LocalizeConfig{MessageID: id})
}

// ListLanguages loops all translated languages
// Parameters: name is like "English", id is like "en"
func ListLanguages(fun func(name, id string)) {
	if i18nBundle == nil {
		return
	}
	for _, tag := range i18nBundle.LanguageTags() {
		fun(display.Self.Name(tag), tag.String())
	}
}
